from django.contrib.auth import authenticate, login
from rest_framework import serializers
from .models import Article, Like
from django.contrib.auth.models import User


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(label='用户名', write_only=True)
    password = serializers.CharField(label='密码', write_only=True)


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password', 'is_staff']
        # 勾选is_staff属性，否则创建用户不能登录

    def create(self, validated_data):  # 用于创建应该新用户对象
        # validated_data是一个字典，它包含了经过验证后的数据。
        user = User(**validated_data)
        user.set_password(validated_data['password'])  # 利用set.password()对密码进行加密
        user.save()  # 调用save方法，将新创建的用户实例保存到数据库中。
        return user


class ArticleSerializer(serializers.ModelSerializer):
    likes = serializers.SerializerMethodField()  # 可以在serializer层继续定义临时字段（该文章的点赞列表）

    def get_likes(self, obj):  # obj指的是文章
        # 从数据库中获取与指定文章相关的喜欢此文章的用户的用户名列表
        like = Like.objects.filter(article=obj).values_list("user__username", flat=True)
        return like

        # likes = Like.objects.filter(article=obj).select_related("user")  # 过滤特定文章的点赞记录
        # usernames = [like.user.username for like in likes]  # 提取每个点赞用户的用户名
        # return usernames  # 返回用户名列表

    class Meta:
        model = Article
        fields = '__all__'

        read_only_fields = ['auther', 'like_count']

    # 此处逻辑与view中的perform_create效果一样
    def create(self, validated_data):  # 用于创建应该新文章对象
        print(validated_data)  # 打印字典内容
        auther = self.context['request'].user  # 获取当前用户
        validated_data['auther'] = auther  # 当前用户 auther 添加到 validated_data 字典中，用于指明新创建文章的作者。
        return Article.objects.create(
            **validated_data)  # 调用 Article 模型的 objects.create() 方法，解包 validated_data 字典中的数据，以创建新文章的实例。返回值是新创建的文章对象。


class LikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Like
        fields = ['user', 'article']


class BookSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=255)
    auth = serializers.CharField(max_length=255)
    count = serializers.IntegerField()
    createtime = serializers.DateField(input_formats=["%Y-%m-%d"])
    desc = serializers.CharField(max_length=500)

    @staticmethod
    def from_elasticsearch_response(response):
        # 提取结果
        hits = response.get('hits', {}).get('hits', [])
        # 将结果转换为适合 Django REST framework 的格式
        articles = [hit['_source'] for hit in hits]
        return articles

    def to_representation(self, instance):
        return super().to_representation(instance)
